from urllib.request import Request, build_opener, HTTPCookieProcessor
from fake_useragent import UserAgent
from http.cookiejar import MozillaCookieJar
from urllib.parse import urlencode

# 登录

# 保存Cookie到文件中
def get_cookie():
    login_url = "https://mail.qq.com/"
    headers = {
        "User-Agent": UserAgent().chrome
    }
    form_data = {
        "ptui_loginuin": "939403831",
        "qm_antisky": "939403831&d7e3297941b9857db361acae6e07c7fb7ca1202fd01a3421b4d3394b0805bca3",
        # "": ""
    }
    f_data=urlencode(form_data).encode()
    request = Request(login_url, headers=headers,data=f_data)
    cookie_jar = MozillaCookieJar()
    handler = HTTPCookieProcessor(cookie_jar)
    opener = build_opener(handler)
    response = opener.open(request)
    # 俩个参数表示无论是否过期都保存起来
    cookie_jar.save("cookie.txt", ignore_expires=True, ignore_discard=True)


def use_cookie():
    info_url="https://mail.qq.com/"
    headers = {
        "User-Agent": UserAgent().chrome
    }
    request = Request(info_url, headers=headers)
    cookie_jar = MozillaCookieJar()
    cookie_jar.load("cookie.txt",ignore_discard=True,ignore_expires=True)
    handler = HTTPCookieProcessor(cookie_jar)
    opener = build_opener(handler)
    response = opener.open(request)
    print(response.read().decode("utf-8","ignore"))

# 获取cookie从文件中

# 访问页面
if __name__ == '__main__':
    # get_cookie()
    use_cookie()